<template>
  <div class="container">
    <el-card class="box-card" shadow="always">
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form inline @submit.native.prevent="search">
            <el-form-item label="搜索">
              <el-input
                v-model="searchForm.queryConditions"
                clearable
                placeholder=""
                prefix-icon="el-icon-search"
                size="medium"
              />
            </el-form-item>
            <el-form-item label="产品类型">
              <el-select v-model="productTypeList.productType" clearable placeholder="全部" style="width:150px;" @change="productTypeSelected">
                <el-option v-for="item in productTypeList" :key="item.id" :value="item.id" :label="item.productType" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button native-type="submit" size="medium" type="primary"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">

          <el-button icon="el-icon-download" type="primary" class="btn">
            <a download :href="exportUrl"> 导出 </a>
          </el-button>

          <el-button
            class="btn"
            type="primary"
            icon="el-icon-circle-plus-outline"
            @click="addProjectDialog"
            >添加</el-button
          >
          
        </el-col>
      </el-row>
      <div>
        <el-table :data="list" border style="width: 100%" v-loading="projectLoading">
          <el-table-column type="index" width="50" label="序号" align="center"/>
          <el-table-column prop="projectName" label="项目名称" align="center"/>
          <el-table-column label="所属类型" align="center">
            <template slot-scope="scope">
              {{scope.row.typeBriefInfo.productType}}
            </template>
          </el-table-column>
          <el-table-column prop="creator" width="150" label="创建者" align="center"/>
          <el-table-column prop="createTime" width="150" label="创建时间" align="center"/>
          <el-table-column prop="modifier" width="150" label="修改者" align="center"/>
          <el-table-column prop="updateTime" width="150" label="修改时间" align="center"/>
          
          <el-table-column label="操作" fixed = "right" width="150" align="center">
            <template slot-scope="scope">
              <el-tooltip content="查看信息" placement="top">
                <el-button
                  icon="el-icon-search"
                  circle
                  @click="showDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="编辑信息" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  @click="editProjectDialog(scope.row)"
                />
              </el-tooltip>
              <el-tooltip content="删除管理员" placement="top">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteProduct(scope.row)"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          :current-page="paging.current"
          :page-sizes="paging.pageSizes"
          :page-size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <Dialog
        :visible="projectInfoVIsible"
        :data="projectInfo"
        @cancel="cancel"
      />
      <edit-dialog
        :index="index"
        :product-type-list="productTypeList"
        :title="dialogTitle"
        :visible="editDialogVisible"
        :project-info="projectInfo"
        @cancel="cancel"
        @ok="ok"
      />
    </el-card>
  </div>
</template>

<script>
import {
  getAllProjectInfosByConditions,
  deleteProjectInfoById,
  addProject,
  updateProject,
} from "@/api/project.js";
import { getProductTypeBriefInfos } from '@/api/productType'
import Dialog from "./components/Dialog";
import EditDialog from "./components/editDialog";

export default {
  name: "ProjectManage",
  components: { Dialog, EditDialog },
  data() {
    return {
      searchForm: {
        queryConditions: "",
        typeId: ''
      },
      productTypeList: [],
      list: [],
      paging: {
        total: 0,
        current: 1,
        pageSizes: [5, 10, 15],
        size: 5,
      },
      projectInfoVIsible: false,
      projectInfo: {},
      editDialogVisible: false,
      projectLoading: false,
      dialogTitle: "",
      index: 0, // 0 添加；1 编辑；2 查看信息
      // headers: {
      //   Authorization: getToken(),
      // },
    };
  },
  computed: {
    exportUrl() {
      return process.env.VUE_APP_BASE_API + "/exportProjectExcel";
    },
  },
  created() {
    this.projectLoading = true;
    this.getData();
    this.getProductType()
    // console.log(getToken())
  },
  methods: {
    async getProductType() {
      const result = await getProductTypeBriefInfos()
      this.productTypeList = result.data
      // console.log('@@@@',this.productTypeList)
    },
    search() {
      this.paging.current = 1;
      this.projectLoading = true;
      this.getData();
    },
    getData() {
      const form = {
        ...this.searchForm,
        page: this.paging.current,
        pageSize: this.paging.size,
      };
      getAllProjectInfosByConditions(form).then(({ data }) => {
        console.log(data);
        this.list = data.projectInfos;
        //this.paging.size = data.size
        this.paging.total = data.totalCount;
        this.projectLoading = false;
      })
      .catch((err) => {
          // 如果没有数据就显示为空
          this.list = [];
          // 返还每页显示的条数
          //this.paging.size = res.data.size;
          this.paging.total = 0;
          this.projectLoading = false;
        });;
    },
    handleSizeChange(val) {
      this.paging.current = 1;
      this.paging.size = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.paging.current = val;
      this.getData();
    },
    showDialog(row) {
      this.projectInfoVIsible = true;
      this.projectInfo = row;
      this.index = 2;
    },
    deleteProduct(row) {
      this.$confirm("此操作将永久删除这条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const result = await deleteProjectInfoById({ id: row.id, accountId: this.$store.getters.accountId });
          console.log(result);
          if (result.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    productTypeSelected(val) {
      this.searchForm.typeId = val;
      this.search()
    },
    editProjectDialog(row) {
      this.dialogTitle = "编辑产品信息";
      this.editDialogVisible = true;
      this.projectInfo = this.extendCopy(row);
      this.index = 1;
    },
    // 对象的深拷贝
    // 对象进行深拷贝，否则“编辑”框内修改内容也会影响到页面
    extendCopy(p) {
      var c = {};
      for (var i in p) { 
        c[i] = p[i];
      }
      return c;
    },
    addProjectDialog() {
      this.dialogTitle = "添加产品";
      this.editDialogVisible = true;
      this.index = 0;
    },
    cancel() {
      if (this.index === 2) {
        this.projectInfoVIsible = false;
      } else {
        this.editDialogVisible = false;
      }
      this.index = 0;
    },
    editProjectInfo(data) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve, reject) => {
        if (this.index) {
          // 编辑导师信息
          // console.log(val)
          const result = await updateProject(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("修改成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        } else {
          const result = await addProject(data);
          // console.log(res)
          if (result.code === 200) {
            this.$message.success("添加成功");
            resolve(result);
          } else {
            this.$message.error("修改失败，请重试");
            reject(result);
          }
        }
      });
    },
    async ok(val) {
      const response = await this.editProjectInfo(val);
      console.log(response);
      if (response.code === 200) {
        this.editDialogVisible = false;
        this.getData();
        this.index = 0;
      }
    },
    // onSuccess(response, file, fileList) {
    //   console.log(response);
    //   if (response.code !== 200) {
    //     this.$message.error("上传失败，请重试");
    //   } else {
    //     this.$message.success("上传成功");
    //     this.getData();
    //   }
    // },
    // onError(error, file, fileList) {
    //   console.log(error);
    // },
  },
};
</script>
<style lang="scss" scoped>
.el-pagination {
  margin-top: 20px;
  text-align: right;
}
.btn {
  float: right;
  margin-left: 20px;

}

</style>
